//
//  SinaOAuthViewController.swift
//  MySinaWeiBoSwiftProject
//
//  Created by apple on 2016/11/15.
//  Copyright © 2016年 WangChen. All rights reserved.
//

import UIKit
import SVProgressHUD



class SinaOAuthViewController: UIViewController {

    //设置view属性,设置代理
    //设置webView属性
    let webView = UIWebView()
    
    //切换加载的主视图
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    
    //webView加载页面方法
    func loadWebViewRequest() {
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + appKey + "&redirect_uri=" + redirectUrl
        let url = URL(string: urlStr)
        let request = URLRequest(url: url!)
        print(urlStr)
        webView.loadRequest(request)
    }
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //添加关闭按钮
        let closeBtnItem = UIBarButtonItem(title: "关闭", imageName: "navigationbar_back_withtext", target: self, action: #selector(close))
        navigationItem.leftBarButtonItem = closeBtnItem
        
        //添加自动填充按钮
        let autoPutinItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoPutinit))
        navigationItem.rightBarButtonItem = autoPutinItem
        
        //背景颜色
        view.backgroundColor = UIColor.white
        
        //加载request
        loadWebViewRequest()
        
    }
    
    
    //关闭按钮方法
    func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    //自动填充方法
    func autoPutinit() {
        let jsString = "document.getElementById('userId').value = 'qhwc2009@sina.cn', document.getElementById('passwd').value = 'wangchen138714'"
        webView.stringByEvaluatingJavaScript(from: jsString)

    }
    
    
}




//同一个文件中建立一个扩展分类用来实现webView的代理协议,便于管理
extension SinaOAuthViewController: UIWebViewDelegate{
    
    //在开始加载的时候开启菊花
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完毕关闭菊花
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    //http://bbs.itheima.com/forum.php?code=ba22813822809e08a0dcdc0ed170cc50
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //先得到urlStr
        let urlStr = request.url?.absoluteString ?? ""
        //判断urlStr中是否包含了code=
        let flag = "code="
        if urlStr .contains(flag){
            //通过截取字符串获得code
            let query = request.url?.query ?? ""
            let code = (query as NSString) .substring(from: flag.characters.count)
//            print(code)
            
            //访问token
            SinaUserAccountViewModel.shared.accessToken(code: code, finished: { (res) in
                if !res{
                    SVProgressHUD.showError(withStatus: "世界上最远的距离就是他妈的没有网络")
                    return
                }
                
                print("请求成功")
//                UIApplication.shared.keyWindow?.rootViewController = SinaWelcomeViewController()
                //发送通知
                NotificationCenter.default.post(name: NSNotification.Name(changeRootVCNotification), object: "welcome")
                
            })
            //访问成功就不加载页面
            return false
        }
        
        return true
    }
  
    
}
